//
//  SportsChartVC.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/26.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit
import Charts

class SportsChartVC: StepsChartVC {

    @IBOutlet var distanceLabel: UILabel!
    @IBOutlet var calorieLabel: UILabel!
    @IBOutlet var useTimeLabel: UILabel!
    @IBOutlet var useCountLabel: UILabel!
    @IBOutlet var tableView: UITableView!
    @IBOutlet var tableViewHeightConstraint: NSLayoutConstraint!
    
    override var yValGranularitie: Double? { 1 }
    
    private var sportData: SportTotalDataModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(R.nib.chartSportCell)
    }

    override func loadWeekData(_ date: Date) {
        API.getSportTotalData(date, .week, imei: imei) { [weak self] result in
            self?.sportData = result.data
            guard result.suc, let data = result.data else {
                self?.onLoadDataFailed(result.errDesc)
                return
            }
            self?.onLoadSummaryData(data)
            
            let entries = data.dayList.compactMap { unit -> BarChartDataEntry? in
                guard let weekday = unit.weekday else { return nil }
                return BarChartDataEntry(x: Double(weekday), y: Double(unit.useTime) / 60, data: unit)
            }
            self?.didLoadWeekData(entries)
        }
    }
    
    override func loadMonthData(_ date: Date) {
        API.getSportTotalData(date, .month, imei: imei) { [weak self] result in
            self?.sportData = result.data
            guard result.suc, let data = result.data else {
                self?.onLoadDataFailed(result.errDesc)
                return
            }
            self?.onLoadSummaryData(data)
            
            let entries = data.dayList.compactMap { unit -> ChartDataEntry? in
                guard let day = unit.day else { return nil }
                return ChartDataEntry(x: Double(day), y: Double(unit.useTime) / 60, data: unit)
            }
            self?.didLoadMonthData(entries)
        }
    }
    
    override func loadYearData(_ date: Date) {
        API.getSportTotalData(date, .year, imei: imei) { [weak self] result in
            self?.sportData = result.data
            guard result.suc, let data = result.data else {
                self?.onLoadDataFailed(result.errDesc)
                return
            }
            self?.onLoadSummaryData(data)
            
            let entries = data.monthList.compactMap { unit -> BarChartDataEntry? in
                guard unit.month > 0 else { return nil }
                return BarChartDataEntry(x: Double(unit.month), y: Double(unit.useTime) / 60, data: unit)
            }
            self?.didLoadYearData(entries)
        }
    }
    
    func onLoadSummaryData(_ data: SportTotalDataModel) {
        let count = data.sportList.count
        UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseInOut) {
            self.tableViewHeightConstraint.constant = self.tableView.rowHeight * CGFloat(count)
            self.view.layoutIfNeeded()
        } completion: { _ in
            self.tableView.reloadData()
        }
        
        if (data.totalDistance > 0) {
            distanceLabel.text = String(format: "%.2f", data.totalDistance / 1000)
        } else {
            distanceLabel.text = "0.00"
        }
        
        if (data.totalCalorie > 0) {
            calorieLabel.text = String(format: "%.2f", data.totalCalorie / 1000)
        } else {
            calorieLabel.text = "0.00"
        }
        
        if (data.totalTime > 0) {
            useTimeLabel.text = String(format: "%.2f", data.totalTime / 60)
        } else {
            useTimeLabel.text = "0.00"
        }
        
        if (data.totalCount > 0) {
            useCountLabel.text = "\(data.totalCount)"
        } else {
            useCountLabel.text = "0"
        }
    }
}

extension SportsChartVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sportData?.sportList.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier:R.reuseIdentifier.chartSportCell, for: indexPath) as! ChartSportCell
//        let cell = tableView.dequeueCell(R.reuseIdentifier.chartSportCell, for: indexPath)
        if let unit = sportData?.sportList[indexPath.row] {
            cell.update(data: unit)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let unit = sportData?.sportList[indexPath.row],
           let vc = R.storyboard.charts.sportDetailVC() {
            vc.unit = unit
            vc.granularity = granularitie
            vc.start = date.startDate(with: granularitie)
            vc.imei = imei
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}
